<template>
  <div class="system-notification">
    <div class="page-header">
      <h2>系统通知发送</h2>
      <p class="subtitle">向用户发送系统消息通知</p>
    </div>

    <el-card shadow="never" class="notification-form-card">
      <el-form 
        :model="notificationForm" 
        :rules="rules" 
        ref="formRef" 
        label-width="100px"
        @submit.prevent="submitForm"
      >
        <el-form-item label="通知标题" prop="title">
          <el-input 
            v-model="notificationForm.title" 
            placeholder="请输入通知标题"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="通知内容" prop="content">
          <el-input 
            v-model="notificationForm.content" 
            type="textarea" 
            :rows="5" 
            placeholder="请输入通知内容"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>

        <!-- <el-form-item label="跳转链接" prop="targetUrl">
          <el-input 
            v-model="notificationForm.targetUrl" 
            placeholder="可选，点击通知后跳转的页面路径，例如: /dashboard"
          >
            <template #prepend>
              <el-select 
                v-model="urlPrefix" 
                placeholder="路径类型" 
                style="width: 115px;"
              >
                <el-option label="内部路径" value="/" />
                <el-option label="外部链接" value="http://" />
                <el-option label="安全链接" value="https://" />
              </el-select>
            </template>
          </el-input>
          <div class="form-tip">
            <el-icon><InfoFilled /></el-icon>
            内部路径以"/"开头，如"/dashboard"；外部链接请输入完整URL
          </div>
        </el-form-item> -->

        <el-form-item label="接收用户" prop="userIds">
          <div class="user-selection">
            <div class="selection-controls">
              <el-radio-group v-model="userSelectionType" @change="handleSelectionTypeChange">
                <el-radio-button label="all">所有用户</el-radio-button>
                <el-radio-button label="roles">按角色选择</el-radio-button>
                <el-radio-button label="specific">指定用户</el-radio-button>
              </el-radio-group>
              
              <el-button 
                v-if="userSelectionType === 'specific'"
                type="primary" 
                @click="openUserSelectionDialog"
              >
                选择用户
              </el-button>
            </div>
            
            <div class="selected-users-container" v-if="userSelectionType === 'specific'">
              <el-empty 
                v-if="selectedUsers.length === 0" 
                description="未选择任何用户" 
              />
              <el-scrollbar v-else height="200px">
                <div class="selected-users-list">
                  <el-tag 
                    v-for="user in selectedUsers" 
                    :key="user.id"
                    class="user-tag"
                    closable
                    @close="removeSelectedUser(user)"
                  >
                    {{ user.username }} <small>({{ user.nickname || user.email }})</small>
                  </el-tag>
                </div>
              </el-scrollbar>
            </div>
            
            <div v-if="userSelectionType === 'roles'" class="roles-selection">
              <el-checkbox-group v-model="selectedRoles">
                <el-checkbox v-for="role in rolesList" :key="role.id" :label="role.id">
                  {{ role.name }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            发送通知
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户选择对话框 -->
    <el-dialog 
      v-model="userDialogVisible" 
      title="选择用户" 
      width="800px"
      destroy-on-close
    >
      <div class="dialog-search">
        <el-input 
          v-model="userSearchKeyword"
          placeholder="搜索用户名/昵称/邮箱"
          clearable
          @clear="searchUsers"
        >
          <template #append>
            <el-button @click="searchUsers">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      
      <el-table 
        v-loading="usersLoading"
        :data="usersList" 
        border 
        style="width: 100%"
        ref="tableRef"
        @selection-change="handleUserSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="roles" label="角色" width="180">
          <template #default="scope">
            <el-tag 
              v-for="role in scope.row.roles" 
              :key="role.id" 
              size="small" 
              class="role-tag"
            >
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="userPagination.current"
          v-model:page-size="userPagination.pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="userPagination.total"
          @size-change="handleUserSizeChange"
          @current-change="handleUserPageChange"
        />
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUserSelection">
            确认选择 ({{ tempSelectedUsers.length }})
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 发送结果对话框 -->
    <el-dialog
      v-model="resultDialogVisible"
      :title="sendSuccess ? '发送成功' : '发送失败'"
      width="500px"
    >
      <div class="result-content">
        <div class="result-icon">
          <el-icon v-if="sendSuccess" class="success-icon"><CircleCheckFilled /></el-icon>
          <el-icon v-else class="error-icon"><CircleCloseFilled /></el-icon>
        </div>
        <div class="result-message">
          {{ resultMessage }}
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resultDialogVisible = false">关闭</el-button>
          <el-button v-if="sendSuccess" type="primary" @click="handleAfterSuccess">
            继续发送
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { 
  InfoFilled, 
  Search, 
  CircleCheckFilled, 
  CircleCloseFilled 
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { sendSystemNotification } from '@/api/notification';
import { getAllRoles, getUsers, getUsersByRoles, getAllUserIds } from '@/api/admin';

// 表单数据
const notificationForm = reactive({
  title: '',
  content: '',
  targetUrl: '',
  userIds: []
});

// URL 前缀选择
const urlPrefix = ref('/');

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入通知标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度应为 2-50 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入通知内容', trigger: 'blur' },
    { min: 5, max: 500, message: '内容长度应为 5-500 个字符', trigger: 'blur' }
  ],
  userIds: [
    { 
      validator: (rule, value, callback) => {
        if (userSelectionType.value === 'specific' && selectedUsers.value.length === 0) {
          callback(new Error('请至少选择一个用户'));
        } else if (userSelectionType.value === 'roles' && selectedRoles.value.length === 0) {
          callback(new Error('请至少选择一个角色'));
        } else {
          callback();
        }
      }, 
      trigger: 'change' 
    }
  ]
};

// 引用
const formRef = ref(null);
const tableRef = ref(null);

// 状态变量
const submitting = ref(false);
const userSelectionType = ref('specific'); // 'all', 'roles', 'specific'
const selectedUsers = ref([]);
const selectedRoles = ref([]);
const userDialogVisible = ref(false);
const userSearchKeyword = ref('');
const usersLoading = ref(false);
const usersList = ref([]);
const tempSelectedUsers = ref([]);
const rolesList = ref([]);

// 分页
const userPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
});

// 发送结果
const resultDialogVisible = ref(false);
const sendSuccess = ref(false);
const resultMessage = ref('');

// 计算属性: 完整的目标URL
const fullTargetUrl = computed(() => {
  if (!notificationForm.targetUrl) return '';
  
  // 如果已经包含协议或以/开头，直接返回
  if (notificationForm.targetUrl.startsWith('http://') || 
      notificationForm.targetUrl.startsWith('https://') ||
      notificationForm.targetUrl.startsWith('/')) {
    return notificationForm.targetUrl;
  }
  
  // 否则添加选定的前缀
  return urlPrefix.value + notificationForm.targetUrl;
});

// 初始化数据
onMounted(() => {
  fetchRolesList();
});

// 获取角色列表
const fetchRolesList = async () => {
  try {
    const res = await getAllRoles();
    if (res.data.code === 200) {
      rolesList.value = res.data.data || [];
    } else {
      ElMessage.error('获取角色列表失败: ' + res.data.message);
    }
  } catch (error) {
    console.error('获取角色列表异常:', error);
    ElMessage.error('获取角色列表失败');
  }
};

// 处理选择类型变更
const handleSelectionTypeChange = (type) => {
  if (type === 'all') {
    // 所有用户模式，清空其他选择
    selectedUsers.value = [];
    selectedRoles.value = [];
  }
};

// 打开用户选择对话框
const openUserSelectionDialog = () => {
  tempSelectedUsers.value = [...selectedUsers.value];
  userDialogVisible.value = true;
  fetchUsersList();
};

// 获取用户列表
const fetchUsersList = async () => {
  usersLoading.value = true;
  try {
    const params = {
      pageNum: userPagination.current,
      pageSize: userPagination.pageSize,
      keyword: userSearchKeyword.value
    };
    
    const res = await getUsers(params);
    if (res.data.code === 200) {
      usersList.value = res.data.data.records || [];
      userPagination.total = res.data.data.total || 0;
      
      // 预选已选用户
      if (tempSelectedUsers.value.length > 0) {
        // 设置表格选中状态
        nextTick(() => {
          const selectedIds = tempSelectedUsers.value.map(user => user.id);
          usersList.value.forEach(user => {
            if (selectedIds.includes(user.id)) {
              tableRef.value?.toggleRowSelection(user, true);
            }
          });
        });
      }
    } else {
      ElMessage.error('获取用户列表失败: ' + res.data.message);
    }
  } catch (error) {
    console.error('获取用户列表异常:', error);
    ElMessage.error('获取用户列表失败');
  } finally {
    usersLoading.value = false;
  }
};

// 搜索用户
const searchUsers = () => {
  userPagination.current = 1;
  fetchUsersList();
};

// 处理用户选择变更
const handleUserSelectionChange = (selection) => {
  tempSelectedUsers.value = selection;
};

// 确认用户选择
const confirmUserSelection = () => {
  selectedUsers.value = [...tempSelectedUsers.value];
  userDialogVisible.value = false;
};

// 移除已选用户
const removeSelectedUser = (user) => {
  selectedUsers.value = selectedUsers.value.filter(u => u.id !== user.id);
};

// 分页大小变更
const handleUserSizeChange = (size) => {
  userPagination.pageSize = size;
  fetchUsersList();
};

// 分页页码变更
const handleUserPageChange = (page) => {
  userPagination.current = page;
  fetchUsersList();
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 确认发送
      ElMessageBox.confirm(
        '确定要发送此系统通知吗？',
        '发送确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        sendNotification();
      }).catch(() => {});
    }
  });
};

// 发送通知
const sendNotification = async () => {
  submitting.value = true;
  
  try {
    // 准备请求数据
    const requestData = {
      title: notificationForm.title,
      content: notificationForm.content,
      targetUrl: fullTargetUrl.value,
      userIds: []
    };
    
    // 根据选择类型准备用户ID
    if (userSelectionType.value === 'specific') {
      requestData.userIds = selectedUsers.value.map(user => user.id);
    } else if (userSelectionType.value === 'roles') {
      // 获取角色下的所有用户
      const res = await getUsersByRoles(selectedRoles.value);
      if (res.data.code === 200) {
        requestData.userIds = res.data.data || [];
      } else {
        throw new Error('获取角色用户失败: ' + res.data.message);
      }
    } else if (userSelectionType.value === 'all') {
      // 获取所有用户
      const res = await getAllUserIds();
      if (res.data.code === 200) {
        requestData.userIds = res.data.data || [];
      } else {
        throw new Error('获取所有用户失败: ' + res.data.message);
      }
    }
    
    // 检查是否有接收用户
    if (requestData.userIds.length === 0) {
      throw new Error('没有选择任何接收用户');
    }
    
    // 发送请求
    const res = await sendSystemNotification(requestData);
    
    if (res.data.code === 200) {
      sendSuccess.value = true;
      resultMessage.value = `成功向 ${requestData.userIds.length} 名用户发送系统通知！`;
    } else {
      sendSuccess.value = false;
      resultMessage.value = '发送失败: ' + res.data.message;
    }
    
    resultDialogVisible.value = true;
  } catch (error) {
    console.error('发送通知异常:', error);
    sendSuccess.value = false;
    resultMessage.value = '发送失败: ' + (error.response?.data?.message || error.message);
    resultDialogVisible.value = true;
  } finally {
    submitting.value = false;
  }
};

// 成功后处理
const handleAfterSuccess = () => {
  resultDialogVisible.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  notificationForm.title = '';
  notificationForm.content = '';
  notificationForm.targetUrl = '';
  selectedUsers.value = [];
  selectedRoles.value = [];
  userSelectionType.value = 'specific';
  urlPrefix.value = '/';
};
</script>

<style scoped>
.system-notification {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.notification-form-card {
  margin-bottom: 20px;
}

.form-tip {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.form-tip .el-icon {
  margin-right: 5px;
  color: #E6A23C;
}

.user-selection {
  width: 100%;
}

.selection-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.selected-users-container {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  padding: 10px;
  min-height: 100px;
}

.selected-users-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.user-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.dialog-search {
  margin-bottom: 20px;
}

.dialog-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.roles-selection {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  padding: 15px;
}

.role-tag {
  margin-right: 5px;
}

.result-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.result-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.success-icon {
  color: #67C23A;
}

.error-icon {
  color: #F56C6C;
}

.result-message {
  font-size: 16px;
  color: #606266;
  text-align: center;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .selection-controls {
    flex-direction: column;
    gap: 10px;
  }
  
  .el-radio-group {
    width: 100%;
  }
  
  .el-radio-button {
    width: 33.33%;
  }
  
  .roles-selection .el-checkbox {
    display: block;
    margin-left: 0;
    margin-bottom: 8px;
  }
}
</style>